<template>
  <form ref="myForm">
    <a href="javascript:;" class="upload">选择文件
      <input  class="selectImg" type="file" accept="image/*" @change="onChange" />
    </a>
    <el-button type="primary" style="height:30px"  @click="onSubmit($event)" >提交</el-button>

  </form>

  <img
      v-if="previewImage"
      :src="previewImage"
      alt="预览图"
      style="max-width: 100%; max-height: 100px"
  />

  <Cropper
      v-if="cropperVisible"
      :imagePath="imagePath"
      fileType="blob"
      @save="onSave"
      @cancel="onCancel"
  />
</template>
<script >
import {useRouter} from "vue-router"

import axios from "axios";
import { reactive, toRefs, ref } from "vue";
import Cropper from "vue3-cropper";
import "vue3-cropper/lib/vue3-cropper.css";
import {ElMessage} from "element-plus";
const URL = window.URL || window.webkitURL;
export default {
  components: { Cropper },
  setup() {
    const router=useRouter()
    // cropper状态
    const state = reactive({
      cropperVisible: false,
      imagePath: "",
      previewImage: null,
    });

    // 获取图片
    const onChange = (e) => {
      const file = e.target.files[0];
      state.imagePath = URL.createObjectURL(file);
      state.cropperVisible = true;
    };

    // 保存选取的图片
    const onSave = (res) => {
      if (typeof res === "string") {
        state.previewImage = res;
      } else {
        state.previewImage = URL.createObjectURL(res);
      }
      state.cropperVisible = false;
    };

    // 取消选取
    const onCancel = () => {
      state.cropperVisible = false;
    };

    // 提交表单——上传文件
    const myForm = ref(null);
    const onSubmit = (e) => {

      let userjson=sessionStorage.getItem('user')
      let user=JSON.parse(userjson)


      let formData = new FormData();
      formData.append('file', document.querySelector('input[type=file]').files[0])
      formData.append("username", user.username);
          if(state.previewImage===null){
            ElMessage.error("未上传头像")
          }else {
            axios({
              method: "post",
              // 提交地址
              url: "/api/changeImage",
              data: formData,
            }).then((res) => {
              if (res.data.code === '1') {
                ElMessage.success('上传成功')
                sessionStorage.setItem('user', JSON.stringify(res.data.data))
                location.reload()

                router.push('/auditor')

              } else {

                ElMessage.error('上传失败')
              }

            })
            // 关闭提交表单
            e.preventDefault();
          }
    };

    return {
      ...toRefs(state),
      onChange,
      onSave,
      onCancel,
      myForm,
      onSubmit,
    };
  },
};
</script>
<style scoped>
/* .upload{
padding: 4px 10px;
height: 20px;
position: relative;
border-style: none;
background-color: rgb(64,158,255);
color: white;
margin-right: 100px;
} */
/* .change{
position: absolute;
overflow: hidden;
right: 0;
top: 0;
opacity: 0;
} */
.upload{
  padding: 4px 10px;
  height: 40px;
  line-height: 30px;
  position: relative;
  border: 1px solid #999;
  text-decoration: none;
  color: white;
  background-color: rgb(64,158,255);
  margin-right: 100px;
  border-radius: 5px;
}
.selectImg{
  position: absolute;
  overflow: hidden;
  right: 0;
  top: 0;
  opacity: 0;
}
</style>